import ImportData from "@/components/ImportData";
import { getFullTreeByXid, getTreeNodeInfoById, getUserInfoByXId, s_freezeuser, s_saveUserInfo } from "@/services/basis";
import { EyeFilled } from "@ant-design/icons";
import { ActionType, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormText, ProTable } from "@ant-design/pro-components";
import { FormattedDateParts, useRequest } from "@umijs/max";
import { Button, Card, Col, DatePicker, Flex, Form, Input, message, Modal, Radio, Row, Space, Tag, Tree, TreeDataNode } from "antd";
import { set, times } from "lodash";
import moment from "moment";
import { useRef, useState } from "react";

const App:React.FC=()=>{

    const [trNode,setTrNode]=useState<{key:any,title:string}>({key:0,title:''});
    const [trData,setTrData]=useState<TreeDataNode[]>([]);
    const [etype,setEtype]=useState(1);
    const [open,setOpen]=useState(false);
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [selectedUser,setSelectedUser]=useState<any>([]);

    const [selectedKeys,setSelectedKeys]=useState<any[]>([]);//存放左侧树节点选中后，下级所有的key,用于快捷调出下属所有的用户组织ID

    const form_ref=useRef<ProFormInstance>();
    const user_ref=useRef<ActionType>();
    const [expandKeys,setExpandKeys]=useState([]);

    useRequest(()=>getFullTreeByXid({x_id:1,treeType:'base_organization'}),{
        onSuccess:(data)=>{
          setTrData(data.ctree);
          setExpandKeys(data.keys);
        },
    });

    interface DataType{
        id:number,
        code:string,
        name:string,
        sex:number,
        roles:string,
        org_name:string,
        status:number,
        operate_time?:string,
        operater_id?:string,
        //---------------------------新增----------------
        workcode:string,
        isuser:number,
        isbusiness:number,
        injob_time:string,
        outjob_time:string,
        nickname:string,
        password:string,
        mobilephone:string,
        email:string,
        creditcode:string,
        org_id:number,
    }

    const columns:ProColumns<DataType>[]=[
        {dataIndex:'id',title:'ID',hidden:true},
        {dataIndex:'org_name',title:'所属部门',},
        {dataIndex:'code',title:'用户编码'},
        {dataIndex:'name',title:'用户姓名'},
        {dataIndex:'sex',title:'性别',render:(text)=>text==1?<>男</>:<>女</>},
        {dataIndex:'creditcode',title:'身份证号'},
        {dataIndex:'mobilephone',title:'手机号'},
        {dataIndex:'roles',title:'所属角色'},
       
        {dataIndex:'workcode',title:'工号'},
        {dataIndex:'isuser',title:'是否用户',render:(text)=>text==1?<>是</>:<Tag color="red">否</Tag>},
        {dataIndex:'isbusiness',title:'是否业务员',render:(text)=>text==1?<>是</>:<Tag color="red">否</Tag>},
        {dataIndex:'injob_time',title:'入职时间',
            render:(text)=>text==''?<></>:moment(moment(text?.toLocaleString()).toDate()).format('YYYY-MM-DD'),
        },
        {dataIndex:'outjob_time',title:'离职时间',
            render:(text)=>text?.toString().length==1?<></>:moment(moment(text?.toLocaleString()).toDate()).format('YYYY-MM-DD'),
           
        },
        {dataIndex:'nickname',title:'呢称'},
        {dataIndex:'password',title:'密码',hidden:true},
        {dataIndex:'email',title:'Email',hidden:true},
        
        {dataIndex:'operate_time',title:'修改时间',
            render:(text)=>moment(moment(text?.toLocaleString()).toDate()).format('YYYY-MM-DD')},
        {dataIndex:'status',title:'状态',fixed:'right',width:60,
            render:(text)=>{
                switch(text){
                    case 1: return <>正常</>;break;
                    case 2: return <Tag color='blue'>冻结</Tag>;break;
                    case 3: return <Tag color='red'>删除</Tag>;break;
                }
            },
        },
      
    ];
    
    var arr:any[]=[];
    //定义一个递归函数，获取选中节点下的所有key
    function getNodeKeys(node:{key:any,title:any,children:any[]}){
         if(node.children&&node.children.length>0)
               node.children.map((item:any)=>{
                  arr.push(item.key);
                  if(item.children.length>0){
                       arr.push(getNodeKeys(item));
                  }
              });
       }
    async function getTreeNodeInfo(node:any){
         //  alert(JSON.stringify(node));
        // setEtype(0);
         setTrNode(node);//保存当前的id，在新增时使用
    //     const info=await getTreeNodeInfoById({treeType:'v_organization',key:node.key});
    //     const fdata={...info.data,
    //                  operate_time:moment(moment(info.data.operate_time).toDate()).format('YYYY-MM-DD')
    //           };

    //    form_ref.current?.setFieldsValue({
    //              code:fdata.code,name:fdata.name,higher_name:fdata.higher_name,
    //              operate_time:fdata.operate_time,higher_code:fdata.higher_code,
    //              status:fdata.status,operater_id:fdata.operater_id,
    //              type:fdata.type,x_id:fdata.x_id,
    //              }); 
       arr=[];//先置为空，再取数据
       arr.push(node.key);
       getNodeKeys(node);
       setSelectedKeys(arr.filter((item)=>item!=null));//当前选中的组织的所有下级ID

    // const {data}=await getUserInfoByXId({x_id:1,org_ids:arr,user_id:0});  //注意传入要用本地变量，可能state未重新渲染前未刷新
     user_ref.current?.reloadAndRest?.();

      }
  
      async function addUser(){
        if(trNode.key==0)
            message.warning('请先选择用户所对应的部门。');
        else{
         setEtype(1);
         setOpen(true);
        };
      }
      
      async function editUser(){
        if(selectedUser.length==0)
            message.warning('请先选择要编辑的用户。');
        else
          {
            setEtype(0);
           setOpen(true);
          }

      }

      async function saveUser(){
        const fdata=form_ref.current?.getFieldsValue();
        //修正日期格式
        const fdata2={...fdata,
           id:etype==0?selectedUser[0].id:0,   //id在编辑时需设置，否则忽略。
           org_id:etype==0?fdata.org_id:trNode.key,
           dep_id:etype==0?fdata.dep_id:trNode.key,
           injob_time:fdata.injob_time?moment(moment(fdata.injob_time).toDate()).format('YYYY-MM-DD HH:mm:ss'):null,
           outjob_time:fdata.outjob_time?moment(moment(fdata.outjob_time).toDate()).format('YYYY-MM-DD HH:mm:ss'):null,
           operate_time:fdata.operate_time?moment(moment(fdata.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'):null,
        };
        //alert(JSON.stringify(fdata2));
        const x=await s_saveUserInfo({x_id:1,operater_id:1,etype,fdata:fdata2});
        if(x.success){
            setEtype(1);
            message.success('用户信息保存成功。');
            user_ref.current?.reloadAndRest?.();
            setSelectedUser([]);
        }
        else
            message.error('用户信息保存失败，请检查！')
        setOpen(false);
      }

      //冻结或删除用户
      async function freeze(etype:number){
        if(selectedUser.length==0)
            message.warning('请先选择用户。');
        else{
          const id=selectedUser[0].id;
          const x=await s_freezeuser({etype,id});
          if(x.success){
             message.success('更新成功！');
             user_ref.current?.reloadAndRest?.();
          }else
             message.error('更新失败，请检查。');
            }
      }

    //   ===============================================================================================================
    return(
     <Row gutter={8} >
         <Col span={6}>
         <Card title='组织架构' style={{height:700}}>
            {/* <Tree treeData={trData} defaultExpandAll 
              onClick={(e,node)=>getTreeNodeInfo(node)}/> */}

             <Tree treeData={trData}   blockNode={true}  expandedKeys={expandKeys}
               onClick={(e,node)=>getTreeNodeInfo({key:node.key,title:node.title?.toString()})}
               onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
            />
         </Card>
         </Col>
         <Col span={18}>
         <Card title='用户基本信息' style={{height:700,overflow:'auto'}}
            extra={<Space>
                   <Button onClick={()=>addUser()}>新增/用户信息无法正常操作</Button>
                   <Button onClick={()=>editUser()}>编辑</Button>
                   <Button onClick={()=>form_ref.current?.submit()}>保存</Button>
                   <span>|</span>
                   <Button onClick={()=>freeze(2)}>冻结</Button>
                   <Button onClick={()=>freeze(3)}>删除</Button>
                   <Button onClick={()=>freeze(1)}>恢复</Button>
                   <ImportData  x_id={1} source='importdata' tdata={{data:'person'}} operater_id={1}  />
                </Space>}
         >
            {/* {JSON.stringify(trNode)}{JSON.stringify(selectedUser)} */}
             <ProTable<DataType>
                actionRef={user_ref}
                columns={columns}
                rowKey='id'
                search={false}
                rowSelection={{
                    type:'radio',
                    selectedRowKeys,
                    fixed:'left',
                 }}
                scroll={{x:'200%',y:430}}
                request={async (params)=>{
                    var user_id=0;
                    if(selectedUser.length!=0)
                        user_id=selectedUser[0]?.id;
                    const x=await getUserInfoByXId({x_id:1,org_ids:selectedKeys,user_id:0});//按树下级多节点获取用户
                    return {
                        data:x.data[0],
                        success:true,
                    };
                }}
                
                pagination={{
                    showQuickJumper:true,
                    pageSize:9,
                }}
                onRow={(record,index)=>{
                    return {
                        onClick:(e)=>{ 
                            setSelectedRowKeys([record.id]);
                            setSelectedUser([record]);
                         },
                    };
                  }}
                
                />
         </Card>
         </Col>
         {/* 弹出用户编辑窗体 */}
         <Modal title={etype==1?'新增用户信息':'编辑用户信息'} open={open} destroyOnClose maskClosable={false}
           onCancel={()=>setOpen(false)} width={900} onOk={()=>saveUser()}
         >
         <ProForm labelCol={{span:8}}  submitter={false} style={{width:800,marginLeft:60}} formRef={form_ref}
            onFinish={()=>saveUser()}
            initialValues={
                etype==0?{
                    ...selectedUser[0],
                    injob_time:moment(moment(selectedUser[0].injob_time).toDate()).format('YYYY-MM-DD'),
                    outjob_time:selectedUser[0].outjob_time?moment(moment(selectedUser[0].outjob_time).toDate()).format('YYYY-MM-DD'):null,
                    operate_time:moment(moment(selectedUser[0].operate_time).toDate()).format('YYYY-MM-DD'),

                   }:{
                      injob_time:moment(moment().toDate()).format('YYYY-MM-DD'),
                      operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),
                      isuser:1,isbusiness:1,sex:1,status:1,
                      org_name:trNode.title.substring(trNode.title.indexOf(' ')+1),
                      operater_id:1,
                   }
            }
         >
            <Row gutter={8}>
                <Col span={10}>
                <ProFormText name='code' label='用户编码' rules={[{required:true,message:'用户编码必须输入'}]}/>
                <ProFormText name='name' label='用户姓名' rules={[{required:true,message:'用户姓名必须输入'}]}/>
                <ProFormText name='creditcode' label='身份证号'/>
                <ProFormText name='mobilephone' label='手机号'  rules={[{required:true,message:'手机号必须输入'}]}/>
                <ProFormRadio.Group name='sex' label='性别' 
                     options={[{label:'男',value:1},{label:'女',value:2}]}/>
                <ProFormText name='org_name' label='所属部门'/>
                <ProFormText name='workcode' label='工号'/>
                <ProFormText name='nickname' label='呢称'/>
                <ProFormText.Password name='password' label='密码'/>
                </Col>
                <Col span={4}></Col>
                <Col span={10}>
                <ProFormText name='email' label='电子邮箱'/>
                <ProFormDatePicker name='injob_time' label='入职日期'/>
                <ProFormDatePicker name='outjob_time' label='离职日期'/>
                <ProFormRadio.Group name='isuser' label='是否用户'
                    options={[{label:'是',value:1},{label:'否',value:0}]} />
                <ProFormRadio.Group name='isbusiness' label='是否业务员'
                    options={[{label:'是',value:1},{label:'否',value:0}]} />
                
                <ProFormRadio.Group name='status' label='状态' 
                       options={[{label:'正常',value:1},
                       {label:'冻结',value:2,style:{color:'blue'}},
                       {label:'删除',value:3,style:{color:'red'}}]}/>
                <ProFormText label='角色' name='roles'/>
                <ProFormDatePicker name='operate_time' label='最近修改时间'/>
                <ProFormText name='operater_id' label='最近修改人'/>
                <ProFormText name='org_id' hidden/>
                <ProFormText name='dep_id' hidden/>
                </Col>
            </Row>
           </ProForm>
         </Modal>
     </Row>
);
}

export default App;